import argparse
import calendar
import time
import sys
import os
import MySQLdb

from progressbar import progressbar
# 路径
path = "file"
# 后缀
filetype = ".md"
mysqlconfig={
    "host":"localhost",
    "user" : "typecho",
    "passwd" :"2Zwmnh2rJKmrdGPZ", 
    "dbname" :"typecho",
    "charset":"utf8mb4"
    }
# 把目录下的所有文件路径含名抓出来
def get_file_path_by_name(file_dir,filetype=".md"):
    menuObj={}
    # end=1
    idx=0
    for root, dirs, files in os.walk(file_dir):  # 获取所有文件
      
        for file in files:  # 遍历所有文件名
         
            if os.path.splitext(file)[1] == filetype:
                # 处理格式：分割文件名
                
                # 去掉文件后面三个字符，得到文件名
                title=file[:-3]
                # 删除文件路径前面5个字符获得目录名
                menu=root[5:]
                itemObj={"root":os.path.join(root, file),"menu":menu,"file":file,"title":title,"idx":idx}
                if menu not in menuObj:
                    menuObj[menu]=[]
                menuObj[menu].append(itemObj)
    return menuObj
# 通过文件名地址 读取文件内的内容 返回字符串内容
def getFileContent(filename):
    # data = get_file_path_by_name(path)
    # for i in range(len(filenamelist)):
    with open(filename, 'r', encoding="UTF-8", errors="ignore") as f:
        return f.read()

def start():
    dbTableMenu="typecho_metas"
    dbTableContent="typecho_contents"
    conn = MySQLdb.connect(host=mysqlconfig["host"], port=mysqlconfig["port"],user =mysqlconfig["user"],passwd =mysqlconfig["passwd"], db = mysqlconfig["dbname"],charset=mysqlconfig["charset"])
    insert_sql='INSERT INTO '+dbTableContent+'(title,text,parent,authorId,created,modified) VALUES(%s,%s,%s,1,%s,%s)'
    insert_data=[]
    insertMenu_sql='INSERT INTO '+dbTableMenu+'(name,description,type,slug) VALUES(%s,%s,"category","")'
    cur=conn.cursor()
    allfileName = get_file_path_by_name(path)
    
    count=len(allfileName)
    idx=1
    pb = progressbar(count)
    for k in allfileName:
        # print(type(k))
        # return
        cur.execute('SELECT mid FROM '+dbTableMenu+' WHERE name = %s LIMIT 1',(k,))
        item =cur.fetchone()
        caId=0
        # print(item[0])
        if item==None:
            # return
                # 插入菜单数据
            cur.execute(insertMenu_sql, (k,k))
            caId=cur.lastrowid
            print(cur.lastrowid)
            # 最新插入行的主键id
            print(conn.insert_id())
            #提交数据
            conn.commit()
        else:
            caId=item[0]
            # print("caid=",caId)

        items =allfileName[k]
        for item in items:
           
            content =getFileContent(item["root"])
            cur.execute('SELECT cid FROM '+dbTableContent+' WHERE title = %s AND parent = %s LIMIT 1',(item["title"],caId,))
            (item1) =cur.fetchone()
            if item1==None:
                # insert_data=(item["title"],content,caId)
                # insert_data.append((item["title"],content,caId))
                # 批量插入菜单数据
                # cur.executemany(insert_sql,insert_data)
                # 时间戳
                utc_time = calendar.timegm(time.gmtime())
                cur.execute(insert_sql,(item["title"],"<!--markdown-->"+content,caId,utc_time,utc_time,))
                # caId=cur.lastrowid
                print(cur.lastrowid)
                # 最新插入行的主键id
                print(conn.insert_id())
                #提交数据
                conn.commit()
            # print(item1)
        idx=idx+1
        pb.progress(idx)
            # return
    #提交之后，再关闭 cursor 和链接
    cur.close()
    conn.close()
    return
# 路径
path = "file"
# 后缀
filetype = ".md"
mysqlconfig={
    "host":"localhost",
    "user" : "typecho",
    "passwd" :"2Zwmnh2rJKmrdGPZ", 
    "dbname" :"typecho",
    "charset":"utf8mb4",
    "port":3306
 }
if __name__ == "__main__":
    print("#################### 查看帮助命令 -h ########################")
    print("######完整命令 --dbcharset utf8mb4  --dbhost localhost --dbname typecho  --dbpasswd 123456 --dbport=3306 --dbuser root  --filesuffix .md  --path file ######")
    print("############################启动中################################")
    parser = argparse.ArgumentParser(description='argparse testing')
# parser.add_argument('--dbhost','-n',type=str, default = "bk",required=True,help="a programmer's name")
# parser.add_argument('--dbuser','-a',type=int, default=35,help='age of the programmer')
    parser.add_argument('--dbhost','-dh',type=str, default='localhost',required=False,help="数据库地址默认 localhost")
    parser.add_argument('--dbuser','-du',type=str, default='root',required=False,help="数据库用户名 默认 root")
    parser.add_argument('--dbpasswd','-dpwd',type=str, default='123456',required=False,help="数据库密码 默认 123456")
    parser.add_argument('--dbport','-dp',type=int, default=3306,required=False,help="数据库端口号 默认 3306")
    parser.add_argument('--dbname','-dn',type=str, default='typecho',required=False,help="数据库名 默认 typecho")
    parser.add_argument('--dbcharset','-dc',type=str, default='utf8mb4',required=False,help="数据库字符集 默认 utf8mb4")
    parser.add_argument('--path','-p',type=str, default='file',required=False,help="文档所在路径 默认 file ")
    parser.add_argument('--filesuffix','-f',type=str, default='.md',required=False,help="文档后缀 默认 .md")
# parser.add_argument('--favorite','-f',type=str, nargs="+",required=False,help="favorite of the programmer")
    args = parser.parse_args()
# 路径目录
    path=args.path
    # 文档后缀
    filetype=args.filesuffix
    mysqlconfig["host"]=args.dbhost
    mysqlconfig={
        "host":args.dbhost,
        "user" : args.dbuser,
        "passwd" :args.dbpasswd, 
        "dbname" :args.dbname,
        "charset":args.dbcharset,
        "port":args.dbport
        }
        
    print(args)
    start()
